<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const map = ref(null)
const mapContainer = ref(null)
const currentPosition = ref(null) // 当前位置

const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: '3e19bdcaa753e3ba70600ca4c0b1a8c3',
      version: '2.0',
      plugins: ['AMap.Scale', 'AMap.ToolBar']
    })

    map.value = new AMap.Map(mapContainer.value, {
      zoom: 17,
      center: [116.667171, 23.654933],
      viewMode: '3D'
    })

    // 显示实时路况
    const trafficLayer = new AMap.TileLayer.Traffic({
      zIndex: 10
    })
    map.value.add(trafficLayer)

    // 添加控件
    map.value.addControl(new AMap.Scale())

    // 标记
    const marker = new AMap.Marker({
      position: [116.667171, 23.654933],
      title: '我的位置'
    })
    map.value.add(marker)

    // 信息窗口
    const infoWindow = new AMap.InfoWindow({
      content: '<div class="p-2">我的位置</div>',
      offset: new AMap.Pixel(0, -30)
    })

    marker.on('click', () => {
      infoWindow.open(map.value, marker.getPosition())
    })

  } catch (error) {
    console.error('地图加载失败:', error)
  }
}
onMounted(initMap)
onBeforeUnmount(() => {
  if(map.value) map.value.destroy()
})
</script>

<template>
  <div ref="mapContainer" class="map"></div>
</template>

<style scoped>
.map {
  height: 91vh !important;
  width: 100%;
}
</style>
